/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.felisberto.serialfwder.socket.server;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 *
 * @author Filipe
 */
public class NettyServerHandler extends SimpleChannelUpstreamHandler {

    private final NettyServer server;
    private NettySession session;

    public NettyServerHandler(NettyServer server) {
        this.server = server;
    }
    private static final Logger logger = Logger.getLogger(
            NettyServerHandler.class.getName());

    @Override
    public void handleUpstream(
            ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            logger.info(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    @Override
    public void channelDisconnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        if(session != null){
            logger.info("Channel closed");
        }
        server.sessionClosed(session);
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.log(
                Level.WARNING,
                "Unexpected exception from downstream.",
                e.getCause());
        e.getChannel().close();
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
        session = new NettySession(ctx.getChannel());
        server.newSession(session);
        logger.info("Channel Created!");

    }

}
